//
//  NewFeatureViewController.swift
//  LVWeibo
//
//  Created by lv on 15/6/27.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import FFAutoLayout

private let reuseIdentifier = "Cell"

class NewFeatureViewController: UICollectionViewController {
    
    // 界面布局
    let layout = UICollectionViewFlowLayout()
    
    // 实现 init() 简化外部调用
    init() {
        super.init(collectionViewLayout: layout)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 注册可重用cell
        self.collectionView?.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    //MARK:- 设置布局属性
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        print(collectionView?.frame)
        // 设置布局
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        // 设置分页
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    }
    
    
    //MARK:- UICollectionViewDataSource
    let imageCount = 4
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell

        cell.imageIndex = indexPath.item
        return cell
    }
    
    ///  滑动cell结束后代理方法
    ///
    ///  :param: collectionView collectionView
    ///  :param: cell           前一个显示cell
    ///  :param: indexPath      前一个显示cell的indexPath
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        // 获取当前显示cell的indexPath
        let path = collectionView.indexPathsForVisibleItems().last!
        
        // 判断当为最后一个cell时，播放按钮显示动画
        if path.item == imageCount - 1 {
            (collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell).showStartButton()
        }
    }
    
    
    //MARK:- 隐藏状态栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

//MARK:- 定义 NewFeatureCell
class NewFeatureCell: UICollectionViewCell {
    
    
    //MARK:- 动画显示'开始按钮'
    private func showStartButton() {
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        startButton.hidden = false
        startButton.userInteractionEnabled = false
        
        UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
                // 恢复按钮之前的状态
                self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                print("OK")
                self.startButton.userInteractionEnabled = true
        }
    }
    
    //MARK:- 开始按钮点击事件
    func startButtonClick() {
        // 发送通知 object: true表示显示主控制器
        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchMainInterfaceNotification, object: true)
    }
    
    //MARK:- 懒加载子控件
    // IconView
    private lazy var iconView: UIImageView = {
        return UIImageView()
        }()
    
    // 懒加载'开始按钮'
    private lazy var startButton: UIButton = {
        let btn = UIButton()
        btn.frame = CGRectMake(0, 0, 105, 36)
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        // 添加按钮点击事件
        btn.addTarget(self, action: "startButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
    
    // 图片索引
    var imageIndex = 0 {
        didSet {
            iconView.image = UIImage(named:"new_feature_\(imageIndex + 1)")
            self.startButton.hidden = true
        }
    }
    //MARK:- 实例化
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconView)
        addSubview(startButton)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:- 重置按钮布局
    override func layoutSubviews() {
        super.layoutSubviews()
        iconView.frame = bounds
        
        // 设置按钮布局（一定要在实例化时设置自动布局）
        startButton.ff_AlignInner(ff_AlignType.BottomCenter, referView: self, size: nil, offset: CGPoint(x: 0, y: -160))
    }
}

